package com.xiaojiehzu.jex.client.config;

import com.xiaojiehzu.jex.client.exception.TooManyConfigException;
import com.xiaojiehzu.jex.client.util.ScanClassUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Set;

/**
 * @author 朱小杰
 * 时间 2017-11-05 .13:30
 * 说明 注解配置加载器
 */
public class AnnotationConfigLoader implements ConfigLoader {
    public final static Logger LOG = LoggerFactory.getLogger(AnnotationConfigLoader.class);
    private AnnotationConfigLoader(){}
    /**
     * 是否支持
     */
    private boolean support = false;
    /**
     * 是否初始化
     */
    private boolean init = false;
    private JexConfiguration jexConfiguration;
    @Override
    public synchronized boolean isSupport() {
        initConfig();
        return this.support;
    }

    @Override
    public JexConfiguration getConfiguration() {
        if(!init){
            initConfig();
        }
        return this.jexConfiguration;
    }

    private void initConfig(){
        if(!init){
            LOG.info("加载jex注解配置");
            this.init = true;
            Set<Class<?>> classes = ScanClassUtil.findClassWithAnotation(EnableJex.class);
            if(classes != null && classes.size() > 0){
                if(classes.size() > 1){
                    StringBuffer sb = new StringBuffer();
                    for(Class<?> c : classes){
                        sb.append(c.getName());
                    }
                    this.support = false;
                    throw new TooManyConfigException(EnableJex.class.getName() + " 的配置太多\n" + sb.toString());
                }else{
                    resolveConfig(classes.iterator().next());
                    this.support = true;
                }
            }else{
                this.support = false;
            }
        }
    }

    private void resolveConfig(Class<?> clazz){
        EnableJex enableJex = clazz.getAnnotation(EnableJex.class);
        String appName = enableJex.appName();
        String[] serverAddress = enableJex.serverAddress();

        JexConfiguration jexConfiguration = new JexConfiguration();
        jexConfiguration.setAppName(appName);

        jexConfiguration.setServerAddress(Arrays.asList(serverAddress));

        this.jexConfiguration = jexConfiguration;
    }




    /**
     * 获取唯一实例
     * @return
     */
    public static AnnotationConfigLoader getInstance(){
        return Instance.instance;
    }
    private static class Instance{
        private final static AnnotationConfigLoader instance = new AnnotationConfigLoader();
    }
}
